<?php
    header('content-type:text/html;charset="utf-8"');

    //定义一个统一的返回格式
    $responseData = array("code" => 0, "message" => "");


    // var_dump($_POST);
    //将前端传输到后端的数据全部加载在页面上
    $username = $_POST['username'];
    $password = $_POST['password'];
    
    //先给所有获取到的数据做一个简单的表单验证
    if(!$username){
        $responseData['code'] = 1;
        $responseData["message"] = "用户名不能为空";
        //将数据按统一数据返回格式返回
        echo json_encode($responseData);
        exit;
    }

    if(!$password){
        $responseData['code'] = 2;
        $responseData["message"] = "密码不能为空";
        //将数据按统一数据返回格式返回
        echo json_encode($responseData);
        exit;
    }
    //接着判断用户名是否已经被注册
    //链接数据库
    $link = mysqli_connect("localhost", "root", "123456",'midea');

    //判断数据库是否链接成功
    if(!$link){
        $responseData['code'] = 4;
        $responseData["message"] = "服务器忙";
        //将数据按统一数据返回格式返回
        echo json_encode($responseData);
        exit;
    }
    mysqli_set_charset($link, "utf8");

    //准备sql验证是否已经被注册
	//准备sql语句进行登录
	$sql = "SELECT * FROM username WHERE username='{$username}' AND password='{$password}'";

	$res = mysqli_query($link, $sql);
    $row = mysqli_fetch_assoc($res);
	if(!$row){
		$responseData['code'] = 4;
		$responseData['message'] = "用户名或密码错误";
		echo json_encode($responseData);
		exit;
	}else{
		$responseData['message'] = "登录成功";
		$responseData["username"] = $row['username'];
		echo json_encode($responseData);
	}

	mysqli_close($link);
?>